package com.lambkit.module.cms.web.directive;

import com.jfinal.kit.StrKit;
import com.jfinal.template.Env;
import com.jfinal.template.io.Writer;
import com.jfinal.template.stat.Scope;
import com.lambkit.module.cms.rpc.model.CmsArticle;
import com.lambkit.module.cms.rpc.model.CmsCategory;
import com.lambkit.web.directive.LambkitDirective;
import com.lambkit.web.directive.annotation.JFinalDirective;

import java.util.List;

/**
 * 
 * @author Henry Yang 杨勇 (gismail@foxmail.com)
 * @version 1.0
 * @Package com.lambkit.module.cms.web.directive
 */
@JFinalDirective("categoryArticles")
public class CategoryArticlesDirective extends LambkitDirective {

    @Override
    public void onRender(Env env, Scope scope, Writer writer) {

        Long categoryId = getParaToLong("categoryId", scope);
        String flag = getPara("categoryFlag", scope);

        if (StrKit.isBlank(flag) && categoryId == null) {
            throw new IllegalArgumentException("#categoryArticles(categoryFlag=xxx，categoryId=xxx) is error, " +
                    "categoryFlag or categoryId must not be empty. " + getLocation());
        }

        //Boolean hasThumbnail = getParaToBool("hasThumbnail", scope);
        String orderBy = getPara("orderBy", scope, "order_number desc,id desc");
        int count = getParaToInt("count", scope, 10);

        CmsCategory category = categoryId != null
                ? CmsCategory.service().findById(categoryId)
                : CmsCategory.service().findFirstByFlag(flag);
        if (category == null) {
            return;
        }

        scope.setLocal("category", category);

        List<CmsArticle> articles = CmsArticle.service().findListByCategoryId(category.getId(), orderBy, count);
        if (articles == null || articles.isEmpty()) {
            return;
        }

        scope.setLocal("articles", articles);
        renderBody(env, scope, writer);
    }


    @Override
    public boolean hasEnd() {
        return true;
    }
}
